// MapViewerGlobal.qml(仙工智能地图解析)
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15

Window {
    id: mapWindow
    title: "地图视图"
    visible: false
    minimumWidth: 400
    minimumHeight: 300

    property real initialWidth: 800
    property real initialHeight: 600
    width: initialWidth
    height: initialHeight

    // 窗口居中逻辑
    onVisibleChanged: {
        if (visible) {
            setGeometry(
                (Screen.width - width) / 2,
                (Screen.height - height) / 2,
                Math.min(Screen.width * 0.8, initialWidth),
                Math.min(Screen.height * 0.8, initialHeight)
            )
        }
    }

    Canvas {
        id: canvas
        renderTarget: Canvas.FramebufferObject
        anchors.fill: parent
        property real currentScale: 1.0
        property real offsetX: width / 2
        property real offsetY: height / 2

        // 窗口大小变化时重定位地图
        onWidthChanged: resetMapView()
        onHeightChanged: resetMapView()

        function resetMapView() {
            if (pointModel.count > 0) 
                calculateCenter();
            canvas.requestPaint();
        }

        MouseArea {
            anchors.fill: parent
            acceptedButtons: Qt.LeftButton | Qt.RightButton
            property real lastX: 0
            property real lastY: 0

            onPositionChanged: {
                if (pressedButtons & Qt.LeftButton) {
                    canvas.offsetX += mouse.x - lastX;
                    canvas.offsetY += mouse.y - lastY;
                    lastX = mouse.x;
                    lastY = mouse.y;
                    canvas.requestPaint();
                }
            }

            onWheel: {
                const zoomFactor = 1.1;
                const scaleDelta = (wheel.angleDelta.y > 0) ? zoomFactor : 1/zoomFactor;
                canvas.currentScale *= scaleDelta;
                
                // 精确的缩放中心计算
                canvas.offsetX = (canvas.offsetX - wheel.x) * scaleDelta + wheel.x;
                canvas.offsetY = (canvas.offsetY - wheel.y) * scaleDelta + wheel.y;
                canvas.requestPaint();
            }

            onPressed: {
                lastX = mouse.x;
                lastY = mouse.y;
            }
        }

        onPaint: {
            const ctx = getContext("2d");
            ctx.resetTransform();
            ctx.clearRect(0, 0, width, height);
            
            // 仙工智能地图坐标系适配
            ctx.translate(offsetX, offsetY);
            ctx.scale(currentScale, -currentScale);
            const visibleLeft = (-offsetX) / currentScale;
            const visibleTop = (offsetY - height) / currentScale; 
            const visibleRight = (width - offsetX) / currentScale;
            const visibleBottom = offsetY / currentScale;
            
            // 绘制点集（灰色）
            ctx.fillStyle = "gray";
            const pointRadius = Math.max(0.5, 3 / canvas.currentScale); // 动态半径[1](@ref)
            for (let i = 0; i < pointModel.count; i++) {
                const p = pointModel.get(i);
                const x = p.x * 10 + 100;
                const y = p.y * 10;
                // 跳过屏幕外点
                if (x < visibleLeft || x > visibleRight || y < visibleTop || y > visibleBottom) continue;
                ctx.beginPath();
                ctx.arc(p.x * 10 + 100, p.y * 10, pointRadius, 0, Math.PI * 2); // 使用动态半径
                ctx.fill();
            }

            // 绘制机器人位置和ID (蓝色)
            for (let i = 0; i < robotModel.count; i++) {
                const r = robotModel.get(i);
                const x = r.x * 10 + 100;  // 与地图相同的转换
                const y = r.y * 10;
                
                // 绘制机器人位置（蓝色大圆点）
                ctx.fillStyle = "blue";
                ctx.beginPath();
                ctx.arc(x, y, 8, 0, Math.PI * 2);
                ctx.fill();
                
                // 绘制ID文本（需要临时恢复Y轴方向）
                ctx.save();
                ctx.scale(1, -1); // 反转Y轴使文本正常显示
                ctx.textAlign = "center";
                ctx.textBaseline = "bottom";
                ctx.fillStyle = "black";
                ctx.font = "bold 14px sans-serif";
                // 计算文本位置（考虑当前缩放）
                const textY = -y + 15 * (1/currentScale); 
                ctx.fillText(r.id, x, textY);
                ctx.restore();
            }
        }

    ListModel { id: pointModel }
    ListModel { id: robotModel }

    // 计算地图中心点（仙工智能坐标系适配）
    function calculateCenter() {
        let minX = Infinity, maxX = -Infinity;
        let minY = Infinity, maxY = -Infinity;
        
        for (let i = 0; i < pointModel.count; i++) {
            const p = pointModel.get(i);
            const x = p.x * 10 + 100;
            const y = p.y * 10;  // 仙工智能地图Y坐标不需要翻转
            
            minX = Math.min(minX, x);
            maxX = Math.max(maxX, x);
            minY = Math.min(minY, y);
            maxY = Math.max(maxY, y);
        }
        
        const centerX = (minX + maxX) / 2;
        const centerY = (minY + maxY) / 2;
        const contentWidth = maxX - minX + 40;
        const contentHeight = maxY - minY + 40;
        
        // 动态调整窗口（限制最大尺寸）
        initialWidth = Math.min(Screen.width * 0.8, Math.max(minimumWidth, contentWidth));
        initialHeight = Math.min(Screen.height * 0.8, Math.max(minimumHeight, contentHeight));
        
        // 精确的中心点补偿（适配变换链）
        canvas.offsetX = canvas.width / 2 - centerX * canvas.currentScale;
        canvas.offsetY = canvas.height / 2 + centerY * canvas.currentScale; // +号适配Y轴翻转
    }
    
    Component.onCompleted: {
        canvas.offsetX = canvas.width / 2;
        canvas.offsetY = canvas.height / 2;
        
        // 在 pointsUpdated 信号处理中：
        mapData.pointsUpdated.connect(points => {
            pointModel.clear();
            // 动态采样：缩放越大，采样越密集
            const lodFactor = Math.max(1, Math.floor(1 / canvas.currentScale)); 
            const sampleStep = Math.max(1, Math.floor(points.length / (5000 * lodFactor)));
            
            for (let i = 0; i < points.length; i += sampleStep) {
                pointModel.append({ "x": points[i].x, "y": points[i].y });
            }
            calculateCenter();
            canvas.requestPaint();
        });
        
        mapData.robotsUpdated.connect(() => {
            const robots = mapData.getRobots();
            robotModel.clear();
            robots.forEach(r => robotModel.append(r));
            canvas.requestPaint();
        });

        mapData.loadMap("data/robot1001/map/default.smap");
    }
    }
}